import React from 'react'
import {withRouter} from 'react-router'
import BaseComponent from 'basecomponent'
import classNames from 'classnames'
import icons from 'icons'
import Button from "button"
import Dropzone from 'react-dropzone'
import './style.scss'
import {Form, Select, Checkbox} from 'antd'
const FormItem = Form.Item
import api from 'apis'
const Option = Select.Option
import appConfig from 'config'
import {USER_KEY} from 'auth'
import store from 'store'

class Job extends BaseComponent {
  constructor() {
    super(...arguments)
    const location = this.props.location
    this.state = {
      isRevise: location.state ? location.state.revise : false,
      jobData: {
        Id: location.query.Id?  parseInt(location.query.Id) : -1,
        Image: '',
        Company: {Id: location.state?  parseInt(location.state.companyId) : -1},
        Name: '',
        Area: location.state?  parseInt(location.state.area) : '',
        Salary: '',
        Exp: '',
        Edu: '',
        Introduce: '',
      },
      jobLogoImg: '',
      jobLogoPreview: '',
      currentPage: 1,
      pageSize: 5,
      provinceData: [],
      cityData: [],
    }
    store.set('currentJobId', location.query.Id ? location.query.Id : 1)
  }

  componentDidMount() {
    const {jobData} = this.state
    if(this.handleID()){
      console.log(jobData)
      this.getJobDetail(jobData.Id)
    }else {
      this.getProvinceInfo(this.props.location.state?  parseInt(this.props.location.state.area) : '')
    }
  }

  getJobDetail(id) {
    let jobId = id ? id : store.get('currentJobId')
    this.getJobDetailRP = api.company.getJobDetail(jobId)
    this.registerRequest(this.getJobDetailRP.request)
    this.getJobDetailRP.promise
      .then((res) => {
        res.Data && this.setState({jobData: res.Data})
        res.Data && this.mapJobData(res.Data)
      })
  }

  reviseCollege(text, record) {
    this.props.router.push({
      pathname: 'home/revise/college',
      query: {Id: record.Id},
      state: {
        revise: true,
      }
    })
  }

  watchCollege(text, record) {

  }

  mapJobData(detail) {
    this.props.form.setFieldsValue({
      Name: detail.Name,
      Introduce: detail.Introduce,
      Salary: detail.Salary,
      Exp: detail.Exp,
      Edu: detail.Edu
    })
    this.getProvinceInfo(parseInt(detail.Area / 1000) * 1000, detail.Area)
    this.setState({
      jobLogoPreview: `${appConfig.apiHost}/File/?pid=${detail.Image}&key=${store.get(USER_KEY)}`,
    })
  }

  getProvinceInfo(Pid, Cid) {
    this.getProviceRP = api.address.getProvince()
    this.registerRequest(this.getProviceRP.request)
    this.getProviceRP.promise
      .then((res) => {
        res.Data && this.setState({provinceData: res.Data})
        res.Data && this.props.form.setFieldsValue({
          AddrP: Pid.toString(),
        })
        this.getCityInfo(Pid, Cid)
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  getCityInfo(Pid, Cid) {
    this.getCityRP && this.getCityRP.request.abort()
    this.getCityRP = api.address.getCity(Pid)
    this.registerRequest(this.getCityRP.request)
    this.getCityRP.promise
      .then((res) => {
        res.Data && this.setState({cityData: res.Data})
        res.Data && this.props.form.setFieldsValue({
          AddrP: Pid.toString(),
          AddrC: Cid.toString(),
        })
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  handleProvinceSelect(value, option) {
    if (value) {
      this.getCityRP && this.getCityRP.request.abort()
      this.getCityRP = api.address.getCity(value)
      this.registerRequest(this.getCityRP.request)
      this.getCityRP.promise
        .then((res) => {
          res.Data && this.setState({cityData: res.Data, defaultProvince: value})
          res.Data && this.props.form.setFieldsValue({
            AddrC: res.Data[0].Id.toString()
          })
        })
        .catch((err) => {
          alert(err.msg)
        })
    }

  }

  handleLogoFileSelect(files) {
    const {jobData} = this.state
    let file = files[0]
    if (file) {
      this.uploadLogoRP && this.uploadLogoRP.request.abort()
      this.uploadLogoRP = api.file.uploadFile(file)
      this.registerRequest(this.uploadLogoRP.request)
      this.uploadLogoRP.promise
        .then((res) => {
          this.setState({
            jobLogoImg: res.Data || '', jobData: Object.assign({},
              jobData, {Image: res.Data || ''})
          })
        })
        .catch((err) => {
          alert(err.msg)
        })
    }
  }

  handleSubmit(e) {
    e.preventDefault()
    const{jobData} = this.state
    this.props.form.validateFields((err, values) => {
      if (!err) {
        jobData.Name = values.Name
        jobData.Area = values.AddrC
        jobData.Introduce = values.Introduce
        jobData.Exp = values.Exp
        jobData.Edu = values.Edu
        jobData.Salary = values.Salary
        if (this.handleID()){
          this.reviseJobRP && this.reviseJobRP.request.abort();
          this.reviseJobRP = api.company.reviseJob(jobData.Id, jobData);
          this.registerRequest(this.reviseJobRP.request);
          this.reviseJobRP.promise
            .then((res) => {
              res.Data && this.setState({jobData: res.Data});
              alert('修改成功')
            })
            .catch((err) => {
              alert(err.msg)
            })
        } else {
          if(!(jobData.Company.Id === -1 || typeof jobData.Company.Id === 'undefined')){
            this.addJobRP && this.addJobRP.request.abort();
            this.addJobRP = api.company.addJob(jobData);
            this.registerRequest(this.addJobRP.request);
            this.addJobRP.promise
              .then((res) => {
                res.Data && this.setState({jobData: res.Data});
                alert('保存成功')
              })
              .catch((err) => {
                alert(err.msg)
              })
          }
          else{
            alert('添加岗位出错')
          }
        }
      }
    })
  }
  handleID () {
    const {jobData} = this.state
    return !(jobData.Id === -1 || typeof jobData.Id === 'undefined')
  }

  getLogoImgDiv() {
    const {jobLogoImg, jobLogoPreview} = this.state
    if (jobLogoPreview.length > 0) {
      return <img className={'preview-img'} src={jobLogoPreview}/>
    } else {
      if (jobLogoImg.length > 0) {
        return <img className={'preview-img'}
                    src={`${appConfig.apiHost}/File/?pid=${jobLogoImg}&key=${store.get(USER_KEY)}`}/>
      } else {
        return <div className={'default-wrapper'}>
          <img className={'image-default'} src={icons.uploadImg}/>
          <span>点击添加LOGO</span>
        </div>
      }
    }
  }

  render() {
    const {wrapperName, buttonWrapperName, clickBack, children} = this.props
    const {getFieldDecorator, getFieldsError, getFieldError, isFieldTouched} = this.props.form
    const {provinceData, cityData, jobData
    } = this.state
    const self = this
    return (
      children ? <div>{children}</div> :
        <div className={'sem-main-content'}>
          <div className={classNames('company-wrapper', wrapperName)}>
            <div className={classNames('button-wrapper', buttonWrapperName)}>
              <Button className={'back-button'} onClick={() => {
                  this.props.router.goBack()
              }}>{Button.AddOn({
                src: icons.backIcon, style: {
                  width: '1rem',
                  height: '1rem',
                  display: 'block',
                  backgroundRepeat: 'no-repeat',
                }
              })}</Button>
              <div className={'add-name'}>
                添加岗位
              </div>
            </div>
            <Form onSubmit={this.handleSubmit.bind(this)} hideRequiredMark={true}>

              <div className={'body-top'}>
                <Dropzone className={'image-drop-zone'}
                          onDrop={this.handleLogoFileSelect.bind(this)}
                          accept={'image/*'}
                          multiple={false}>
                  {this.getLogoImgDiv()}
                </Dropzone>
                <div className={'body-top-middle'}>
                  <div className={'option-wrapper'}>
                    <div className={'option-title'}>岗位名称</div>
                    <FormItem>
                      {getFieldDecorator('Name', {initialValue: jobData.Name})(
                        <input className={'option-input'}
                               type={'text'}/>
                      )}
                    </FormItem>
                  </div>
                  <div className={'option-wrapper'}>
                    <div className={'option-title'}>公司地址</div>
                    <FormItem>
                      {getFieldDecorator('AddrP')(
                        <Select className={'province-select'}
                                onSelect={this.handleProvinceSelect.bind(this)}
                                notFoundContent={'-'}>
                          {provinceData.map(function (item, index) {
                            return <Option key={item.Id.toString()} value={item.Id.toString()}>{item.Name}</Option>
                          })}
                        </Select>
                      )
                      }
                    </FormItem>
                   <FormItem>
                      {getFieldDecorator('AddrC')(
                        <Select className={'city-select'}
                                notFoundContent={'-'}
                        >
                          {
                            cityData && cityData.map(function (item, index) {
                              return <Option key={item.Id.toString()} value={item.Id.toString()}>{item.Name}</Option>
                            })
                          }
                        </Select>
                      )
                      }
                    </FormItem>
                  </div>
                  <div className={'option-wrapper'} style={{marginBottom: '0'}}>
                    <div className={'option-title'}>薪水范围</div>
                    <FormItem>{
                      getFieldDecorator('Salary')(
                        <input className={'option-input'}/>
                      )
                    }</FormItem>
                  </div>
                </div>
                <div className={'body-top-end'}>
                  <div className={'option-wrapper'}>
                    <div className={'option-title'}>工作年限</div>
                    <FormItem>{
                      getFieldDecorator('Exp')(
                        <input className={'option-input'}
                               type={'text'}/>
                      )
                    }</FormItem>
                  </div>
                  <div className={'option-wrapper'}>
                    <div className={'option-title'}>最低学历</div>
                    <FormItem>{
                      getFieldDecorator('Edu')(
                        <Select className={'option-select'}
                                 notFoundContent={'-'}
                        >
                          <Option key={'初中'} value={'初中'}>{'初中'}</Option>
                          <Option key={'高中'} value={'高中'}>{'高中'}</Option>
                          <Option key={'大专'} value={'大专'}>{'大专'}</Option>
                          <Option key={'本科'} value={'本科'}>{'本科'}</Option>
                          <Option key={'硕士'} value={'硕士'}>{'硕士'}</Option>
                          <Option key={'博士'} value={'博士'}>{'博士'}</Option>
                        </Select>
                      )
                    }
                    </FormItem>
                  </div>
{/*                  <div className={'option-wrapper'} style={{marginBottom: '0'}}>
                    <div className={'option-title'}>公司领域</div>
                    <FormItem>{
                      getFieldDecorator('category')(
                        <input className={'option-input'}
                               type={'text'}/>
                      )
                    }</FormItem>
                  </div>*/}
                </div>
              </div>

              <div className={'body-middle'}>
                <div className={'title-wrapper'}>
                  <span className={'title-bar'}/>
                  <span className={'title-text'}>岗位说明</span>
                  <Button className={'title-btn-save'} buttonType={'submit'} onClick={() => {
                  }}>保存</Button>
                </div>
                <FormItem>{
                  getFieldDecorator('Introduce', {initialValue: jobData.Introduce})(
                    <textarea className={'company-intro'}/>
                  )
                }</FormItem>
              </div>
            </Form>
          </div>
        </div>
    )
  }
}

module.exports = Form.create()(withRouter(Job))
